package com.example.module_happy.viewmodel

import androidx.lifecycle.viewModelScope
import com.example.lib_base.BaseViewModel
import com.example.module_happy.intent.HappyIntent
import com.example.module_happy.model.HappyModel
import com.example.module_happy.state.HappyState
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch

class HappyViewModel:BaseViewModel<HappyIntent>() {
    private val model by lazy{HappyModel()}
    private val mutableState = MutableStateFlow<HappyState>(HappyState.Loading)
    val observerState:StateFlow<HappyState>
    get() = mutableState
    init {
        viewModelScope.launch {
            channel.consumeAsFlow().collect{
                when(it){
                    is HappyIntent.GetMultiType->{
                        val multiType = model.getMultiType()
                        if(multiType.code==0){
                            multiType.data.forEach {
                                it.head="https://ts1.cn.mm.bing.net/th?id=OIP-C.cn_mIqJN0Td_0Ono0xMEsQHaLL&w=120&h=185&c=8&rs=1&qlt=90&o=6&dpr=1.1&pid=3.1&rm=2"
                            }
                            mutableState.value=HappyState.GetTypeSuccess(multiType.data)
                        }else{
                            mutableState.value=HappyState.Failure(multiType.msg)
                        }
                    }
                    is HappyIntent.GetSimpleVideo->{
                        val simpleVideo = model.getSimpleVideo(it.page, it.size)
                        if(simpleVideo.code==0){
                            mutableState.value=HappyState.GetSimpleSuccess(simpleVideo.data)
                        }else{
                            mutableState.value=HappyState.Failure(simpleVideo.msg)
                        }
                    }
                }
            }
        }
    }
}